package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Ages;
import com.itheima.pojo.Sexs;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import com.itheima.utils.DateUtils;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private ReportService reportService;
    //会员数量折线图
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){

        try {
            Map map = new HashMap();
            Calendar calendar = Calendar.getInstance();
            //计算过去一年的12个月
            calendar.add(Calendar.MONTH,-12);//获得当前时间往前推12个月
            List<String> list = new ArrayList<>();

            for(int i=0;i<12;i++){
                calendar.add(Calendar.MONTH,1);//获得去年当前时间加1循环
                Date date = calendar.getTime();
                list.add(new SimpleDateFormat("yyyy.MM").format(date));
            }
            map.put("months",list);
            List<Integer> memberCount = memberService.findByCountByMonths(list);
            map.put("memberCount",memberCount);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    //套餐数据饼图
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        Map map = new HashMap();

        try {
            List<Map<String,Object>> maps = setmealService.findSetmealCount();
            List<String> list = new ArrayList<>();
            for (Map<String, Object> stringObjectMap : maps) {
                String name = String.valueOf(stringObjectMap.get("name"));
                list.add(name);
            }
            map.put("setmealNames",list);
            map.put("setmealCount",maps);
            return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    //性别占比数据饼图
    @RequestMapping("/getSexReport")
    public Result getSexReport(){

        try {
            List<Sexs> sexs=memberService.findMemberSex();
            return new Result(true,"获取性别信息成功",sexs);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"获取性别信息失败");
        }
    }

    //年龄占比数据饼图
    @RequestMapping("/getAgeReport")
    public Result getAgeReport(){

        try {
            List<Ages> ages=memberService.findMemberAge();
            return new Result(true,"获取年龄信息成功",ages);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"获取年龄信息失败");
        }
    }

    //运营数据
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){

        try {
            Map<String,Object> data = reportService.getBusinessReportData();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //导出数据
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){

        try {
            Map<String,Object> data = reportService.getBusinessReportData();
            String reportDate = String.valueOf(data.get("reportDate"));
            Integer todayNewMember = (Integer) data.get("todayNewMember");
            Integer totalMember = (Integer) data.get("totalMember");
            Integer thisWeekNewMember = (Integer) data.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) data.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) data.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) data.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) data.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) data.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) data.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) data.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) data.get("hotSetmeal");

            //获取模板真实路径  File.separator可以自动适应系统的分隔符
            String filepath = request.getSession().getServletContext().getRealPath("template")+ File.separator + "report_template.xlsx";
            //加载模板文件，基于提供的Excel模板文件在内存中创建一个Excel对象
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filepath)));
            //获得第一个工作页
            XSSFSheet sheet = excel.getSheetAt(0);
            //获得第三行
            XSSFRow row = sheet.getRow(2);
            //获得第6个单元格
            XSSFCell cell = row.getCell(5);
            //设置日期
            cell.setCellValue(reportDate);
            //设置新增会员数 在第五行，第6个单元格
             row = sheet.getRow(4);
             cell = row.getCell(5);
             cell.setCellValue(todayNewMember);//设置新增会员数
             cell = row.getCell(7);
             cell.setCellValue(totalMember);//设置总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//设置本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//设置本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            //热门套餐
            int rowNumber = 12;
            //遍历集合
            for (Map map : hotSetmeal) {
                String name = String.valueOf(map.get("name"));
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet.getRow(rowNumber++);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());
            }

            //表格下载 ,基于浏览器作为客户端下载
            OutputStream outputStream = response.getOutputStream();
            //设置响应头信息
            response.setContentType("application/vnd.ms-excel");//代表的是excel文件
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//content-Disposition指定客户端下载的类型以附件类型下载

            excel.write(outputStream);
            outputStream.flush();
            outputStream.close();
            excel.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }


    //导出pdf
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response){

        try {
            Map<String,Object> data = reportService.getBusinessReportData();
            List<Map> hotSetmeal = (List<Map>) data.get("hotSetmeal");

            //获取模板真实路径  File.separator可以自动适应系统的分隔符
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template")+ File.separator + "health_business3.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template")+ File.separator + "health_business3.jasper";

            //编译模板，编译为后缀为jasper的二进制文件
            JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);
            //填充数据
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath,data,new JRBeanCollectionDataSource(hotSetmeal));


            //表格下载 ,基于浏览器作为客户端下载
            OutputStream outputStream = response.getOutputStream();
            //设置响应头信息
            response.setContentType("application/pdf");//代表的是excel文件
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");//content-Disposition指定客户端下载的类型以附件类型下载

            //输出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint,outputStream);


            outputStream.flush();
            outputStream.close();


            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    @RequestMapping("/everyMonthReport")
    public  Result getMemberReport(String dateTime01,String dateTime02) throws ParseException {

        System.out.println(dateTime01);
        System.out.println(dateTime02);
        String[] split = dateTime01.split("-",1);
        String minDate = split[0];
        String[] split1 = dateTime02.split("-",1);
        String maxDate = split1[0];

//        for (int i = st; i <ed ; i++) {
//
//        }

        ArrayList<String> months = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(sdf.parse(minDate));
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        max.setTime(sdf.parse(maxDate));
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

        Calendar curr = min;
        while (curr.before(max)) {
            months.add(sdf.format(curr.getTime()));
            curr.add(Calendar.MONTH, 1);
        }
        List<Integer> memberCount = new ArrayList<>();
        for (String s : months) {
             Integer  count= reportService.findmemberCount(minDate,s);
             memberCount.add(count);
        }

      Map<String,Object> map =  new HashMap<>();
        map.put("months",months);
        map.put("memberCount",memberCount);


        return new Result(true,"查询用户信息成功",map);


    }
}
